package xq.gwt.mvc.model;

public class TimeSpanPropertyModel extends IntegerPropertyModel {	
	private static final long serialVersionUID = 5054385971669543164L;
	
	@Override
	public String getText() {		
		if(getValue() == null)
			return null;
		
		int seconds = getValue();
		int hours = seconds /3600;
		int minutes = (seconds % 3600) / 60;
		int secondsRemaining = (seconds % 3600) % 60;
		String span = hours + ":" + minutes + ":" + secondsRemaining;
		return span;		
	}

	@Override
	public void setText(String text) throws ConversionException{
		setHasError(false);
		if((text == null) ||(text.equals(""))){
			setValue(null);
			return;
		}
		
		if(!text.matches("[0-9]+:[0-9]+:[0-9]+")){
			super.setText(text);
			return;
		}
		
		Integer intVal;
		try {
			String[] parts = text.split(":");		
			int hours = Integer.parseInt(parts[0]);
			int minutes = Integer.parseInt(parts[1]);
			int seconds = Integer.parseInt(parts[2]);
			intVal = hours * 3600 + minutes * 60 + seconds;
			
		} catch (Exception e) {
			ConversionException ce = new ConversionException(e.getLocalizedMessage());
			ce.initCause(e);
			setHasError(true);
			throw ce;
		}
		
		setValue(intVal);
		
	}
	
}
